package com.hengpeng.itfin.service.activity.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.itfin.common.MessageUtil;
import com.hengpeng.itfin.service.activity.RebateService;
import com.hengpeng.itfin.service.impl.BaseServiceImpl;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.en.ActivityStatus;
import com.hengpeng.itfinbase.en.RewardLevel;
import com.hengpeng.itfinbase.en.RewardRebateStatus;
import com.hengpeng.itfinbase.en.RewardUseType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.activity.InvestBackRebateRequest;
import com.hengpeng.itfinbase.persist.Activity;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinbase.persist.RewardRebate;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserRefer;

public class RebateServiceImpl extends BaseServiceImpl implements RebateService {

    @Override
    public ResponseMessage investSendRebate(InvestBackRebateRequest request) {
        if (request.getUserId() == null || request.getActivityType() == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class,
                    RespCodeConstants.CommonCode.DATA_NOT_VALIDATA, "参数错误");
        }
        Activity activity = daoFactory.getActivityDao().getActivityByType(request.getActivityType());
        if (activity.getStatus() != ActivityStatus.ACTIVE) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动已暂停或还未开始");
        }
        Reward levelone = null, leveltwo = null, levelthree = null, levelfour = null;
        Set<Reward> rewards = activity.getRewards();
        Iterator<Reward> iteRewards = rewards.iterator();
        while (iteRewards.hasNext()) {
            Reward r = iteRewards.next();
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELONE) {
                levelone = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTWO) {
                leveltwo = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTHREE) {
                levelthree = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELFOUR) {
                levelfour = r;
            }
        }
        if (levelone == null || leveltwo == null || levelthree == null || levelfour == null) {
            return MessageUtil.getErrorResponseMessage(ResponseMessage.class, RespCodeConstants.CommonCode.TRANS_FAIL,
                    "活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
        }
        /**
         * 第一层返利
         */
        UserRefer leveOneUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(request.getUserId());
        if (leveOneUserRefer != null) {
            UserInfo leveOneUserInfo = daoFactory.getUserInfoDao().get(leveOneUserRefer.getFromUserId());

            RewardRebate leveOneRewardRebate = new RewardRebate();
            leveOneRewardRebate.setActiveId(activity.getId());
            leveOneRewardRebate.setRewardId(levelone.getId()); 
            leveOneRewardRebate.setCreateTime(new Date());
            leveOneRewardRebate.setGettime(new Date());
            leveOneRewardRebate.setMoney(new BigDecimal(Double.parseDouble(levelone.getRewardVal())
                    * request.getInvestMoney()));
            if (levelone.getRewardUseType() == RewardUseType.TANDONE) {
                leveOneRewardRebate.setPaytime(DateTimeUtil.addDate(new Date(), 1));
            } else {
                leveOneRewardRebate.setPaytime(new Date());
            }
            leveOneRewardRebate.setStatus(RewardRebateStatus.UNPAY);
            leveOneRewardRebate.setUpdateTime(new Date());
            leveOneRewardRebate.setUserId(leveOneUserInfo.getId());
            leveOneRewardRebate.setUserName(leveOneUserInfo.getUserName());
            leveOneRewardRebate = daoFactory.getRebateDao().save(leveOneRewardRebate);
            if (leveOneRewardRebate.getId() == null) {
                logger.error("投资返利发放失败！用户[id=" + leveOneUserInfo.getId() + "][返利金额="
                        + leveOneRewardRebate.getMoney().doubleValue()/100 + "元]");
            }
            /**
             * 第二层返利
             */
            UserRefer leveTwoUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(leveOneUserInfo.getId());
            if (leveTwoUserRefer != null) {
                UserInfo leveTwoUserInfo = daoFactory.getUserInfoDao().get(leveTwoUserRefer.getFromUserId());
                RewardRebate leveTwoRewardRebate = new RewardRebate();
                leveTwoRewardRebate.setActiveId(activity.getId());
                leveTwoRewardRebate.setRewardId(leveltwo.getId());
                leveTwoRewardRebate.setCreateTime(new Date());
                leveTwoRewardRebate.setGettime(new Date());
                leveTwoRewardRebate.setMoney(new BigDecimal(Double.parseDouble(leveltwo.getRewardVal())
                        * request.getInvestMoney()));
                if (leveltwo.getRewardUseType() == RewardUseType.TANDONE) {
                    leveTwoRewardRebate.setPaytime(DateTimeUtil.addDate(new Date(), 1));
                } else {
                    leveTwoRewardRebate.setPaytime(new Date());
                }
                leveTwoRewardRebate.setStatus(RewardRebateStatus.UNPAY);
                leveTwoRewardRebate.setUpdateTime(new Date());
                leveTwoRewardRebate.setUserId(leveTwoUserInfo.getId());
                leveTwoRewardRebate.setUserName(leveTwoUserInfo.getUserName());
                leveTwoRewardRebate = daoFactory.getRebateDao().save(leveTwoRewardRebate);
                if (leveTwoRewardRebate.getId() == null) {
                    logger.error("投资返利发放失败！用户[id=" + leveTwoUserInfo.getId() + "][返利金额="
                            + leveTwoRewardRebate.getMoney().doubleValue()/100 + "元]");
                }
                /**
                 * 第三层返利
                 */
                UserRefer leveThreeUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(
                        leveTwoUserInfo.getId());
                if (leveThreeUserRefer != null) {
                    UserInfo leveThreeUserInfo = daoFactory.getUserInfoDao().get(leveThreeUserRefer.getFromUserId());

                    RewardRebate leveThreeRewardRebate = new RewardRebate();
                    leveThreeRewardRebate.setActiveId(activity.getId());
                    leveThreeRewardRebate.setRewardId(levelthree.getId());
                    leveThreeRewardRebate.setCreateTime(new Date());
                    leveThreeRewardRebate.setGettime(new Date());
                    leveThreeRewardRebate.setMoney(new BigDecimal(Double.parseDouble(levelthree.getRewardVal())
                            * request.getInvestMoney()));
                    if (levelthree.getRewardUseType() == RewardUseType.TANDONE) {
                        leveThreeRewardRebate.setPaytime(DateTimeUtil.addDate(new Date(), 1));
                    } else {
                        leveThreeRewardRebate.setPaytime(new Date());
                    }
                    leveThreeRewardRebate.setStatus(RewardRebateStatus.UNPAY);
                    leveThreeRewardRebate.setUpdateTime(new Date());
                    leveThreeRewardRebate.setUserId(leveThreeUserInfo.getId());
                    leveThreeRewardRebate.setUserName(leveThreeUserInfo.getUserName());
                    leveThreeRewardRebate = daoFactory.getRebateDao().save(leveThreeRewardRebate);
                    if (leveThreeRewardRebate.getId() == null) {
                        logger.error("投资返利发放失败！用户[id=" + leveThreeUserInfo.getId() + "][返利金额="
                                + leveThreeRewardRebate.getMoney().doubleValue()/100 + "元]");
                    }

                    /**
                     * 第四层返利
                     */
                    UserRefer leveFourUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(
                            leveThreeUserInfo.getId());
                    if (leveFourUserRefer != null) {
                        UserInfo leveFourUserInfo = daoFactory.getUserInfoDao().get(leveFourUserRefer.getFromUserId());

                        RewardRebate leveFourRewardRebate = new RewardRebate();
                        leveFourRewardRebate.setActiveId(activity.getId());
                        leveFourRewardRebate.setRewardId(levelfour.getId());
                        leveFourRewardRebate.setCreateTime(new Date());
                        leveFourRewardRebate.setGettime(new Date());
                        leveFourRewardRebate.setMoney(new BigDecimal(Double.parseDouble(levelfour.getRewardVal())
                                * request.getInvestMoney()));
                        if (levelfour.getRewardUseType() == RewardUseType.TANDONE) {
                            leveFourRewardRebate.setPaytime(DateTimeUtil.addDate(new Date(), 1));
                        } else {
                            leveFourRewardRebate.setPaytime(new Date());
                        }
                        leveFourRewardRebate.setStatus(RewardRebateStatus.UNPAY);
                        leveFourRewardRebate.setUpdateTime(new Date());
                        leveFourRewardRebate.setUserId(leveFourUserInfo.getId());
                        leveFourRewardRebate.setUserName(leveFourUserInfo.getUserName());
                        leveFourRewardRebate = daoFactory.getRebateDao().save(leveFourRewardRebate);
                        if (leveFourRewardRebate.getId() == null) {
                            logger.error("投资返利发放失败！用户[id=" + leveFourUserInfo.getId() + "][返利金额="
                                    + leveFourRewardRebate.getMoney().doubleValue()/100 + "元]");
                        }
                    }
                }
            }
        }
        return MessageUtil.GetSuccessMessage();
    }
}
